package cn.lixufeng.order.service.impl;

import cn.lixufeng.basic.service.impl.BaseServiceImpl;
import cn.lixufeng.basic.utils.CodeGenerateUtils;
import cn.lixufeng.basic.utils.PageList;
import cn.lixufeng.order.constants.OrderConstants;
import cn.lixufeng.order.domain.AdoptOrder;
import cn.lixufeng.order.domain.OrderAddress;
import cn.lixufeng.order.mapper.AdoptOrderMapper;
import cn.lixufeng.order.mapper.OrderAddressMapper;
import cn.lixufeng.order.query.AdoptOrderQuery;
import cn.lixufeng.order.service.IAdoptOrderService;
import cn.lixufeng.org.domain.Employee;
import cn.lixufeng.org.mapper.EmployeeMapper;
import cn.lixufeng.pay.constants.PayOrderTypeConstants;
import cn.lixufeng.pay.domain.PayBill;
import cn.lixufeng.pay.mapper.PayBillMapper;
import cn.lixufeng.pay.service.IPayBillService;
import cn.lixufeng.pet.domain.Pet;
import cn.lixufeng.pet.mapper.PetMapper;
import cn.lixufeng.user.domain.LoginInfo;
import cn.lixufeng.user.domain.User;
import cn.lixufeng.user.domain.UserAddress;
import cn.lixufeng.user.mapper.UserAddressMapper;
import cn.lixufeng.user.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Map;

@Service
public class AdoptOrderServiceImpl extends BaseServiceImpl<AdoptOrder> implements IAdoptOrderService {

    @Autowired
    private PetMapper petMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserAddressMapper userAddressMapper;

    @Autowired
    private AdoptOrderMapper adoptOrderMapper;

    @Autowired
    private OrderAddressMapper orderAddressMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private PayBillMapper payBillMapper;

    @Autowired
    private IPayBillService payBillService;

    /**
     * 提交领养订单
     * @param params
     * @param loginInfo
     * @return
     */
    @Override
    @Transactional
    public String submit(Map<String, Object> params, LoginInfo loginInfo) {
        // 校验
        Integer serviceMethod = Integer.valueOf(params.get("service_method").toString());// 送货方式
        Long addressId = Long.valueOf(params.get("address_id").toString()) ;// 收货地址id 从t_user_address表得到
        Long payMethod = Long.valueOf(params.get("pay_method").toString());// 支付方式 1 支付宝 2 微信 0银联
        Long petId = Long.valueOf(params.get("pet_id").toString());
        // 点击领养，然后需要修改宠物状态和下架时间，还要绑定领养者
        Pet pet = petMapper.findById(petId);
        User user = userMapper.loadByLoginInfoId(loginInfo.getId());
        pet.setUser_id(user.getId());
        pet.setOffsaletime(new Date());
        pet.setState(0);
        petMapper.update(pet);
        // 创建领养订单
            // 订单本表
        AdoptOrder order = initAdoptOrder(pet, user);
        adoptOrderMapper.add(order);
            // 订单地址表
        UserAddress userAddress = userAddressMapper.findById(addressId);
        OrderAddress orderAddress = initOrderAddress(order, userAddress);
        orderAddressMapper.add(orderAddress);
        // 支付订单并支付
        PayBill paybill = initPayBill(payMethod, user, order);
        payBillMapper.add(paybill);
        // 返回支付接口的响应数据包
        return payBillService.pay(paybill);
        //@TODO  超时未支付自动取消
    }

    /**
     * 抽取的初始化支付单的方法
     * @param payMethod
     * @param user
     * @param order
     * @return
     */
    private PayBill initPayBill(Long payMethod, User user, AdoptOrder order) {
        PayBill bill = new PayBill();
        bill.setDigest(order.getDigest());
        bill.setMoney(order.getPrice());
        bill.setUnionPaySn(order.getPaySn());
        bill.setLastPayTime(new Date(System.currentTimeMillis() + OrderConstants.LAST_PAY_TIME));
        bill.setPayChannel(payMethod);
        bill.setBusinessType(PayOrderTypeConstants.BUSINESS_TYPE_ADOPT);
        bill.setBusinessKey(order.getId());
        bill.setUser_id(order.getUser_id());
        bill.setShop_id(order.getShop_id());
        bill.setNickName(user.getUsername());
        return bill;
    }


    /**
     * 抽取的初始化订单地址方法
     * @param order
     * @param userAddress
     * @return
     */
    private OrderAddress initOrderAddress(AdoptOrder order, UserAddress userAddress) {
        OrderAddress orderAddress = new OrderAddress();
        // 同名拷贝原则
        BeanUtils.copyProperties(userAddress, orderAddress);
        orderAddress.setOrder_id(order.getId());
        orderAddress.setOrderSn(order.getOrderSn());
        return orderAddress;
    }

    /**
     * 抽取的初始化领养订单方法
     * @param pet
     * @param user
     * @return
     */
    private AdoptOrder initAdoptOrder(Pet pet, User user) {
        AdoptOrder order = new AdoptOrder();
        order.setDigest(pet.getName()+"领养订单");
        order.setPrice(pet.getSaleprice());
        String orderSn = CodeGenerateUtils.generateOrderSn(user.getId());
        order.setOrderSn(orderSn);
        order.setPet_id(pet.getId());
        order.setUser_id(user.getId());
        order.setShop_id(pet.getShop_id());
        // 支付超时15分钟自动取消，时间字段抽取到constants了
        order.setLastPayTime(new Date(System.currentTimeMillis() + OrderConstants.LAST_PAY_TIME));
        return order;
    }

    /**
     * 管理页查询领养订单
     * @param query
     * @param loginInfo
     * @return
     */
    @Override
    public PageList<AdoptOrder> admin(AdoptOrderQuery query, LoginInfo loginInfo) {
        Employee employee = employeeMapper.loadByLoginInfoId(loginInfo.getId());
        // 如果商家id不为空
        if(employee.getShop_id()!= null){
            query.setShopId(employee.getShop_id());
        }
        return super.findPage(query);
    }

    /**
     * 网站用户查询我的订单
     * @param query
     * @param loginInfo
     * @return
     */
    @Override
    public PageList<AdoptOrder> user(AdoptOrderQuery query, LoginInfo loginInfo) {
        User user = userMapper.loadByLoginInfoId(loginInfo.getId());
        query.setUserId(user.getId());
        return super.findPage(query);
    }

    @Override
    public void deleteByQuartz(Long orderId) {
        AdoptOrder adoptOrder = adoptOrderMapper.findById(orderId);
        if(adoptOrder.getState() ==0){//这里可能有隐藏的bug
            adoptOrder.setState(-1);
            // 这里可以考虑直接上架宠物  @TODO
            adoptOrderMapper.update(adoptOrder);
            System.out.println("quartz 触发直接取消订单："+orderId);
        }
    }

}
